package cn.gqr.service.impl;

import cn.gqr.entity.Cart;
import cn.gqr.entity.CartOrder;
import cn.gqr.entity.Order;
import cn.gqr.entity.OrderDetail;
import cn.gqr.mapper.CartMapper;
import cn.gqr.service.CartService;
import cn.gqr.service.RemoteOrderService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class CartServiceImpl extends ServiceImpl<CartMapper, Cart> implements CartService {


    @Autowired
    private CartMapper cartMapper;

    @Autowired
    private RemoteOrderService remoteOrderService;

    //添加购物车
    public boolean addShoppingCart(Cart cart) {
        int insert = cartMapper.insert(cart);
        return insert>0;
    }

    //删除购物车
    public boolean removeShoppingCartById(Integer id) {
        int i = cartMapper.deleteById(id);
        return i>0;
    }

    //查询购物车分页
    public Map<String,Object> selectCarts(int start, int num) {

        IPage<Cart> page = new Page(start,num);

        cartMapper.selectPage(page,new QueryWrapper<Cart>());

        Map map = new HashMap();

        map.put("carts",page.getRecords());
        map.put("total",page.getTotal());

        return map;
    }

    //购物车转订单
    @Transactional
    public String placingAnOrder(CartOrder cartOrder) {
        //添加订单
        String orderId = remoteOrderService.insert(cartOrder);

        //删除购物车
        for (OrderDetail od :cartOrder.getOrderDetails()){
            cartMapper.deleteById(od.getCartId());
        }
        return orderId;
    }

}
